package com.tajiang.business.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gprinter.aidl.GpService;
import com.gprinter.command.GpCom;
import com.gprinter.io.GpDevice;
import com.gprinter.io.PortParameters;
import com.gprinter.save.PortParamDataBase;
import com.gprinter.service.GpPrintService;
import com.tajiang.business.R;
import com.tajiang.business.bluetooth.utils.BTPrintUtils;
import com.tajiang.business.common.activity.BaseActivity;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.SharedPreferencesUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.setting.dialog.BTConnectDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PrinterConnectActivity extends BaseActivity {

    private final static String TAG = "PrinterConnectActivity";
    private final static String DEBUG_TAG = "连接打印机";
    private final static String DEVICE_HEAD_NAME = "Gprinter";  //筛选名称以此开头的蓝牙设备

    public static final int INTENT_PORT_SETTINGS = 0;
    private static final int DEFAULT_PRINTER_NUM = 1;
    private final static int FIND_BT_TIME = 2000;        //倒计时6秒之后停止发现蓝牙设备
    private boolean clickedFromNewDevice = false;       //在已经连接的情况下点击了新的设备

    @BindView(R.id.tvNewDevices)
    TextView tvNewDevices;

    @BindView(R.id.lvNewDevices)
    ListView lvNewDevices;

    @BindView(R.id.btBluetoothScan)
    Button btBluetoothScan;

    private List<BluetoothDevice> BlutToothDevices = new ArrayList<BluetoothDevice>();
    private ListViewAdapter mListViewAdapter = null;
    private List<Map<String, Object>> mList = null;
    private PortParameters mPortParams[] = new PortParameters[DEFAULT_PRINTER_NUM];
    private int mPrinterId = BTPrintUtils.PRINTER_ID;     // 默认的打印机ID
    public boolean isConnected = false; // 打印机连接状态

    private String deviceName;                   //实时更新选择搜索出来的设备名称
    private GpService mGpService;
    private PrinterServiceConnection conn = null;

    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            if (mBluetoothAdapter != null && mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {

        }
    }

    private PortParameters mPortParam;
    private BTConnectDialog dialog;
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(DEBUG_TAG, "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 连接蓝牙
     */
    private void connection() {
        conn = new PrinterServiceConnection();
        Log.i("【TEST】", "new PrinterServiceConnection()..connection");
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
        Log.i("【TEST】", "bindService,,,conn,,");
    }

    private void back2ResultActivity() {

        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putBoolean("tv_device_connected", isConnected);
        intent.putExtras(bundle);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    protected void initTopBar() {
        setTitle("连接蓝牙打印机");
        enLeftClickListener(new OnLeftClick() {
            @Override
            public void leftClick() {
                back2ResultActivity();
            }
        });
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_connect_blue_tooth_device);
    }

    @Override
    protected void initData() {
        mPortParam = new PortParameters();
        mPortParam.setPortType(PortParameters.BLUETOOTH);
        LogUtils.e(DEBUG_TAG, "On Create");
        btBluetoothScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                discoveryDevice();
            }
        });
        initPortParam();    //获取上次已连接的（设备名称）和（连接状态）
        initMyView();       //初始化已连接的列表框
        registerPrinterStatueBroadcast();  //注册广播，用于接收打印机连接状态的变更通知
        connection();       //连接打印机服务
        initDeviceList();   //初始化设备列表（用于展示搜索到的蓝牙设备）
//        discoveryDevice(); //进入页面自动搜索蓝牙设备
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (this.isConnected == false) {  //进入页如果没有连接蓝牙面自动搜索蓝牙设备
            discoveryDevice();
        }
    }

    protected void initDeviceList() {
        // Initialize array adapters. One for already paired devices and
        // one for newly discovered devices

//        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
//                R.layout.bluetooth_device_name_item);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.bluetooth_device_name_item);

//        lvPairedDevices.setAdapter(mPairedDevicesArrayAdapter);
//        lvPairedDevices.setOnItemClickListener(mDeviceClickListener);

        lvNewDevices.setAdapter(mNewDevicesArrayAdapter);
        lvNewDevices.setOnItemClickListener(mDeviceClickListener);
        // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mFindBlueToothReceiver, filter);
        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mFindBlueToothReceiver, filter);
        // Get the local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // Get a set of currently paired devices
//        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
//        // If there are paired devices, add each one to the ArrayAdapter
//        if (pairedDevices.size() > 0) {
//            tvPairedDevices.setVisibility(View.VISIBLE);
//            for (BluetoothDevice device : pairedDevices) {
//
//                mPairedDevicesArrayAdapter.add(device.getName() + "\n"
//                        + device.getAddress());
//            }
//        } else {
//            String noDevices = getResources().getText(R.string.none_paired)
//                    .toString();
//            mPairedDevicesArrayAdapter.add(noDevices);
//        }
    }

    private void discoveryDevice() {
        // Indicate scanning in the title
        dialog.setProgressBarEnable(true)
                .setText("正在扫描设备...")
                .setButtonEnable(false)
                .show();
        setProgressBarIndeterminateVisibility(true);
        // Turn on sub-title for new devices
        tvNewDevices.setVisibility(View.VISIBLE);
        lvNewDevices.setVisibility(View.VISIBLE);
        // If we're already discovering, stop it
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // Request discover from BluetoothAdapter
        new MyCountDownTimer(FIND_BT_TIME, FIND_BT_TIME).start();  //倒计时6秒之后停止发现蓝牙设备
        mBluetoothAdapter.startDiscovery();
    }

    /**
     * ---------------初始化--------------
     * 从数据库获取上次存储组的已选设备的相关状态参数
     */
    private void initPortParam() {

        boolean state = getIntent().getBooleanExtra(BTPrinterChooseActivity.CONNECT_STATUS, false);
        PortParamDataBase database = new PortParamDataBase(this);
        mPortParams[mPrinterId] = new PortParameters();
        mPortParams[mPrinterId] = database.queryPortParamDataBase("" + mPrinterId);
        mPortParams[mPrinterId].setPortOpenState(state);
        this.deviceName = mPortParams[mPrinterId].getUsbDeviceName();
        String BluetoothAddr = mPortParams[mPrinterId].getBluetoothAddr();

        Log.d("【TEST】-initPortParam", "PortParamDataBase.state = " + state);
        Log.d("【TEST】-initPortParam", "PortParamDataBase.mPrinterId = " + mPrinterId);
        Log.d("【TEST】-initPortParam", "PortParamDataBase.deviceName = " + deviceName);
        Log.d("【TEST】-initPortParam", "PortParamDataBase.BluetoothAddr = " + BluetoothAddr);

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        Log.e(DEBUG_TAG, "onDestroy ");
        super.onDestroy();
        this.unregisterReceiver(PrinterStatusBroadcastReceiver);
        if (conn != null) {
            unbindService(conn); // unBindService
        }
        // Make sure we're not doing discovery anymore
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // Unregister broadcast listeners
        if (mFindBlueToothReceiver != null) {
            this.unregisterReceiver(mFindBlueToothReceiver);
        }
    }

    @Override
    public void onBackPressed() {
        back2ResultActivity();
    }

    private void initMyView() {
        this.dialog = new BTConnectDialog(this);
        ListView list = (ListView) findViewById(R.id.lvOperateList);
        mList = getOperateItemData();
        mListViewAdapter = new ListViewAdapter(this, mList, mHandler);
        list.setAdapter(mListViewAdapter);
//		list.setOnItemClickListener(new TitelItemOnClickLisener());
//		list.setOnItemLongClickListener(new TitelItemOnLongClickLisener());
    }

    /**
     * 注册广播，接收打印机连接状态变更
     */
    private void registerPrinterStatueBroadcast() {

        IntentFilter filter = new IntentFilter();
        filter.addAction(GpCom.ACTION_CONNECT_STATUS);
        this.registerReceiver(PrinterStatusBroadcastReceiver, filter);

        Log.d("【TEST】", "注册广播,GpCom.ACTION_CONNECT_STATUS");
    }

    /**
     * 选择新蓝牙设备进行配对连接
     */
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
//             Cancel discovery because it's costly and we're about to connect
//            if (isConnected == true) {
//                ToastUtils.showShort("蓝牙设备已连接");
//                return;
//            }

            PrinterConnectActivity.this.clickedFromNewDevice = true;
            mBluetoothAdapter.cancelDiscovery();
            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();

            Log.d("【TEST】", "OnItemClickListener==>" + info);

            String noDevices = getResources().getText(R.string.none_paired).toString();
            String noNewDevice = getResources().getText(R.string.none_bluetooth_device_found).toString();
            Log.i("tag", info);
            if (!info.equals(noDevices) && !info.equals(noNewDevice)) {
                String address = info.substring(info.length() - 17);
                // Create the result Intent and include the MAC address
                mPortParams[mPrinterId].setBluetoothAddr(address);
                mPortParams[mPrinterId].setPortType(mPortParam.getPortType());
                mPortParams[mPrinterId].setIpAddr(mPortParam.getIpAddr());
                mPortParams[mPrinterId].setPortNumber(mPortParam.getPortNumber());
                mPortParams[mPrinterId].setUsbDeviceName(BlutToothDevices.get(arg2).getName());//存储蓝牙设备名

                SetPortParamToView(mPortParams[mPrinterId]);
                if (CheckPortParamters(mPortParams[mPrinterId])) {
                    PortParamDataBase database = new PortParamDataBase(PrinterConnectActivity.this);
                    database.deleteDataBase("" + mPrinterId);
                    database.insertPortParam(mPrinterId, mPortParams[mPrinterId]);   //将设备记录到数据库中
                    PrinterConnectActivity.this.deviceName = BlutToothDevices.get(arg2).getName();
                } else {
                    messageBox(getString(R.string.port_parameters_wrong));
                }
                updateBlueTooth();
            }
        }
    };

    /**
     * 接收蓝牙适配器的搜索广播
     */
    private final BroadcastReceiver mFindBlueToothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            LogUtils.e("bluetooth_test", "BroadcastReceiver.onReceive() ");
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                String name = device.getName() == null ? "" : device.getName();
                //LogUtils.e(TAG, "device.getName() = " + name);
                Log.d("【TEST】", "device.getName() = " + name);
                /**
                 * 只显示以----<Gprinter>-----开头指定的蓝牙设备让用户选择
                 */
                if (name.contains(DEVICE_HEAD_NAME) && !name.equals(PrinterConnectActivity.this.deviceName)) {
                    if (BlutToothDevices.contains(device) == false) {
                        String info = getString(R.string.port);
                        info += getString(R.string.bluetooth);
                        info += "  " + getString(R.string.address);
                        BlutToothDevices.add(device);
                        mNewDevicesArrayAdapter.add(
                                "设备名称：" + device.getName() + "\n" + info + device.getAddress());
                        Log.d("【TEST】", "device.getName(<Gprinter>) = " + device.getName() + " : " + info + " : " + device.getAddress());
                    }
                }
//                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//                    mNewDevicesArrayAdapter.add(device.getName() + "\n"
//                            + device.getAddress());
//                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

                setProgressBarIndeterminateVisibility(false);
                Log.i("tag", "finish discovery" + mNewDevicesArrayAdapter.getCount());
                if (mNewDevicesArrayAdapter.getCount() == 0) {
//                    String noDevices = getResources().getText(
//                            R.string.none_bluetooth_device_found).toString();
//                    mNewDevicesArrayAdapter.add(noDevices);  //没有设备
                    mNewDevicesArrayAdapter.clear();//没有设备
                    BlutToothDevices.clear();//同时清除设备
                }
            }
        }
    };

    /**
     * 广播“打印机连接状态变更
     */
    private BroadcastReceiver PrinterStatusBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            BTPrintUtils.mConnectState = 0;
            if (GpCom.ACTION_CONNECT_STATUS.equals(intent.getAction())) {
                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);
                int id = intent.getIntExtra(GpPrintService.PRINTER_ID, 0);
                Log.d(DEBUG_TAG, "connect status " + type);
                if (type == GpDevice.STATE_CONNECTING) {
                    setProgressBarIndeterminateVisibility(true);
                    SetLinkButtonEnable(ListViewAdapter.DISABLE);
                    mPortParams[id].setPortOpenState(false);
                    Map<String, Object> map;
                    map = mList.get(id);
                    map.put(ListViewAdapter.STATUS,
                            getString(R.string.connecting));
                    mList.set(id, map);
                    map.put(ListViewAdapter.DEVICE_NAME, deviceName);
                    mListViewAdapter.notifyDataSetChanged();

                    Log.d("【BroadcastReceiver】--->", map.toString());

                    PrinterConnectActivity.this.dialog
                            .setProgressBarEnable(true)
                            .setText("蓝牙打印机连接中...")
                            .setButtonEnable(false).show();

                } else if (type == GpDevice.STATE_NONE) {
                    setProgressBarIndeterminateVisibility(false);
                    SetLinkButtonEnable(ListViewAdapter.ENABLE);
                    mPortParams[id].setPortOpenState(false);
                    Map<String, Object> map;
                    map = mList.get(id);
                    map.put(ListViewAdapter.STATUS, getString(R.string.connect));
                    mList.set(id, map);
                    mListViewAdapter.notifyDataSetChanged();
                    //设置蓝牙已断开连接
                    PrinterConnectActivity.this.isConnected = false;

                    if (PrinterConnectActivity.this.dialog.isShowing()) {
                        PrinterConnectActivity.this.dialog.dismiss();
                        ToastUtils.showShort("请检查蓝牙打印机！");
                    }

                    //TODO.....在已经连接蓝牙打印机的情况下，点击了新蓝牙设备，需要再次连接它........
                    if (clickedFromNewDevice == true) {
                        connectOrDisConnectToDevice(mPrinterId);
                        clickedFromNewDevice = false;
                    } else {

                    }
                } else if (type == GpDevice.STATE_VALID_PRINTER) {

                    setProgressBarIndeterminateVisibility(false);
                    SetLinkButtonEnable(ListViewAdapter.ENABLE);
                    mPortParams[id].setPortOpenState(true);
                    Map<String, Object> map;
                    map = mList.get(id);
                    map.put(ListViewAdapter.STATUS, getString(R.string.cut));
                    mList.set(id, map);
                    mListViewAdapter.notifyDataSetChanged();

                    Log.d("【BroadcastReceiver】--->", map.toString());

                    BTPrintUtils.mConnectState = 1;
                    SharedPreferencesUtils.put(SharedPreferencesUtils.FIRST_CONNECT_PRINTER, 1);
                    isConnected = true;

                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                    setProgressBarIndeterminateVisibility(false);
                    SetLinkButtonEnable(ListViewAdapter.ENABLE);
                    messageBox("Please use Gprinter!");
                }
            }
        }
    };

    private String getPortParamInfoString(PortParameters Param) {

        String info = new String();
        info = getString(R.string.port);
        int type = Param.getPortType();
        Log.d(DEBUG_TAG, "Param.getPortType() " + type);
        if (type == PortParameters.BLUETOOTH) {
            info += getString(R.string.bluetooth);
            info += "  " + getString(R.string.address);
            info += Param.getBluetoothAddr();
        } else {
            info = getString(R.string.init_port_info);
        }
        return info;
    }

    void SetPortParamToView(PortParameters Param) {
        Map<String, Object> map;
        map = mList.get(mPrinterId);
        String info = getPortParamInfoString(Param);
        map.put(ListViewAdapter.INFO, info);
        mList.set(mPrinterId, map);
        mListViewAdapter.notifyDataSetChanged();
    }

    void SetLinkButtonEnable(String s) {
        Map<String, Object> map;
        for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {
            map = mList.get(i);
            map.put(ListViewAdapter.BT_ENABLE, s);
            mList.set(i, map);
        }
        mListViewAdapter.notifyDataSetChanged();
    }

    private List<Map<String, Object>> getOperateItemData() {

        Map<String, Object> map;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {
            map = new HashMap<String, Object>();
            if (mPortParams[i].getPortOpenState() == false) {
                this.isConnected = false;
                map.put(ListViewAdapter.STATUS, getString(R.string.connect));
            } else {
                this.isConnected = true;
                map.put(ListViewAdapter.STATUS, getString(R.string.cut));
            }
            String str = getPortParamInfoString(mPortParams[i]);
            map.put(ListViewAdapter.DEVICE_NAME, this.deviceName);
            map.put(ListViewAdapter.INFO, str);
            map.put(ListViewAdapter.BT_ENABLE, "enable");
            list.add(map);
        }
        return list;
    }

//	class TitelItemOnLongClickLisener implements OnItemLongClickListener {
//		@Override
//		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
//									   int arg2, long arg3) {
//			// TODO Auto-generated method stub
//			Log.d(DEBUG_TAG, "TitelItemOnLongClickLisener " + arg2);
//			Intent intent = new Intent(GpPrintService.ACTION_PRINT_TESTPAGE);
//			intent.putExtra(GpPrintService.PRINTER_ID, arg2);
//			sendBroadcast(intent);
//			return true;
//		}
//	}

    class TitelItemOnClickLisener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub]
            mPrinterId = arg2;
            Intent intent = new Intent(PrinterConnectActivity.this, BluetoothDeviceList.class);
            startActivityForResult(intent, INTENT_PORT_SETTINGS);
        }
    }

    /// TODO: 17/4/21 【蓝牙打印】
    void connectOrDisConnectToDevice(int PrinterId) {
        mPrinterId = PrinterId;
        int rel = 0;
        Log.e(DEBUG_TAG, String.valueOf(mPortParams[PrinterId].getPortOpenState()));
        if (mPortParams[PrinterId].getPortOpenState() == false) {   //如果未连接，则连接
            if (CheckPortParamters(mPortParams[PrinterId])) {
                //TODO....ADD...LOADING....
                try {
                    mGpService.closePort(mPrinterId);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                switch (mPortParams[PrinterId].getPortType()) {
                    case PortParameters.BLUETOOTH:
                        try {
                            rel = mGpService.openPort(PrinterId, mPortParams[PrinterId].getPortType(), mPortParams[PrinterId].getBluetoothAddr(), 0);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                }
                GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
                LogUtils.e(DEBUG_TAG, "result :" + String.valueOf(r));
                if (r != GpCom.ERROR_CODE.SUCCESS) {
                    if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                        mPortParams[PrinterId].setPortOpenState(true);
                        Map<String, Object> map = mList.get(PrinterId);
                        map.put(ListViewAdapter.STATUS, getString(R.string.cut));
                        mList.set(PrinterId, map);
                        mListViewAdapter.notifyDataSetChanged();
                    } else {
                        messageBox(GpCom.getErrorText(r));
                    }

                }
            } else {
                messageBox(getString(R.string.port_parameters_wrong));
            }
        } else {     //如果连接，则断开连接
            //TODO....ADD...LOADING....
            Log.d(DEBUG_TAG, "DisconnectToDevice ");
            setProgressBarIndeterminateVisibility(true);
            SetLinkButtonEnable(ListViewAdapter.DISABLE);
            Map<String, Object> map = mList.get(PrinterId);
            map.put(ListViewAdapter.STATUS, getString(R.string.cutting));
            mList.set(PrinterId, map);
            mListViewAdapter.notifyDataSetChanged();
            try {
                mGpService.closePort(PrinterId);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {

            switch (message.what) {
                case ListViewAdapter.MESSAGE_CONNECT:
                    connectOrDisConnectToDevice(message.arg1);
            }
            return false;
        }
    });

    Boolean CheckPortParamters(PortParameters param) {
        boolean rel = false;
        int type = param.getPortType();
        if (type == PortParameters.BLUETOOTH) {
            if (!param.getBluetoothAddr().equals("")) {
                rel = true;
            }
        }
        return rel;
    }

    private void updateBlueTooth() {
        initMyView();
        Message message = new Message();
        message.what = ListViewAdapter.MESSAGE_CONNECT;
        message.arg1 = mPrinterId;
        mHandler.sendMessage(message);
    }

    private void messageBox(String err) {
        Toast.makeText(getApplicationContext(), err, Toast.LENGTH_SHORT).show();
    }

}
